<template>
  <div>
    <!-- 基础信息部分 -->
    <el-card title="基础信息">
      <el-form :model="form" label-width="120px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="仓库编号" prop="warehouseCode">
              <el-input v-model="form.warehouse.whouseNum" disabled></el-input>
            </el-form-item>
            <el-form-item label="仓库容量/m³" prop="warehouseCapacity">
              <el-input placeholder="请输入" v-model="form.warehouse.capacity"></el-input>
            </el-form-item>
            <el-form-item label="仓库主管" prop="manager">
              <el-select 
                v-model="form.warehouse.manager" 
                @change="handleUserChange"
                placeholder="请选择"
                clearable>
                <el-option 
                  v-for="item in users" 
                  :key="item.userID"
                  :label="item.userName" 
                  :value="item.userID">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="仓库地址" prop="wHouseAddr">
              <el-input placeholder="请输入" v-model="form.warehouse.wHouseAddr"></el-input>
            </el-form-item>
            <el-form-item label="排序" prop="sort">
              <el-input placeholder="请输入" v-model="form.warehouse.sort"></el-input>
            </el-form-item>
            <el-form-item label="仓库锁定" prop="lock">
              <el-switch v-model="form.warehouse.lock" />
            </el-form-item>
            <el-form-item label="备注" prop="remark">
              <el-input type="textarea" placeholder="请输入" v-model="form.warehouse.rember"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="仓库名称" prop="whouseName">
              <el-input placeholder="请输入" v-model="form.warehouse.whouseName"></el-input>
            </el-form-item>
            <el-form-item label="库管部门" prop="dementperId">
              <el-select 
                v-model="form.warehouse.dementperId" 
                placeholder="请选择"
                @change="handleDepartmentChange"
                clearable>
                <el-option 
                  v-for="item in departments" 
                  :key="item.depentmentId"
                  :label="item.depentmentName" 
                  :value="item.depentmentId">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="联系电话" prop="contactPhone">
              <el-input v-model="form.warehouse.phone" disabled></el-input>
            </el-form-item>
            <el-form-item label="仓库状态">
              <el-radio-group v-model="form.warehouse.state">
                <el-radio :label="false">启用</el-radio>
                <el-radio :label="true">停用</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>
    <!-- 库位信息部分 -->
    <el-card title="库位信息">
      <el-row>
        <el-col :span="12">
          <el-button type="primary" @click="addLocation">新增</el-button>
          <el-button @click="deleteLocation">删除</el-button>
          <el-button @click="importLocations">导入</el-button>
          <el-button @click="exportLocations">导出</el-button>
        </el-col>
      </el-row>
      <el-table :data="form.locations" border>
        <el-table-column type="selection"></el-table-column>
        <el-table-column label="序号" type="index"></el-table-column>
        <el-table-column prop="locaTionNum" label="库位编号"></el-table-column>
        <el-table-column prop="locaTionName" label="库位名称"></el-table-column>
        <el-table-column prop="locaTionCapacity" label="库位容量/m³"></el-table-column>
        <el-table-column prop="locaTionManage" label="库位主管">
          <template v-slot="scope">
            <p v-if="scope.row.locaTionManage==1">张三</p>
            <p v-if="scope.row.locaTionManage==2">李四</p>
            <p v-if="scope.row.locaTionManage==3">王五</p>
          </template>
        </el-table-column>
        <el-table-column prop="locaTionSort" label="排序"></el-table-column>
        <el-table-column prop="locaTionCStatus" label="库位状态"></el-table-column>
        <el-table-column label="备注" prop="locaTionRember"></el-table-column>
        <el-table-column label="操作">
          <template #default="scope">
            <el-button size="small" @click="editLocation(scope.row)">编辑</el-button>
            <el-button size="small" @click="deleteSingleLocation(scope.row)" type="danger">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
  </div>

<!-- 新增库位弹窗 -->
<el-dialog v-model="dialogFormVisible" title="新增库位" width="500">
<el-form :model="locationForm" ref="locationFormRef">
  <el-form-item label="库位编号" :label-width="formLabelWidth">
    <el-input v-model="locationForm.locaTionNum" autocomplete="off" disabled />
  </el-form-item>
  
  <el-form-item label="库位名称" :label-width="formLabelWidth">
    <el-input v-model="locationForm.locaTionName" autocomplete="off" placeholder="请输入" />
  </el-form-item>
  
  <el-form-item label="库位容量/m³" :label-width="formLabelWidth">
    <el-input v-model="locationForm.locaTionCapacity" autocomplete="off" placeholder="请输入" />
  </el-form-item>
  
  <el-form-item label="库位主管" :label-width="formLabelWidth">
    <el-select v-model="locationForm.locaTionManage" placeholder="请选择">
      <el-option v-for="item in useritems" :label="item.userName" :value="item.userID"></el-option>
    </el-select>
  </el-form-item>
  
  <el-form-item label="库位状态" :label-width="formLabelWidth">
    <el-radio-group v-model="locationForm.locaTionCStatus">
      <el-radio label="启用">启用</el-radio>
      <el-radio label="停用">停用</el-radio>
    </el-radio-group>
  </el-form-item>
  
  <el-form-item label="排序" :label-width="formLabelWidth">
    <el-input v-model="locationForm.locaTionSort" autocomplete="off" placeholder="请输入" />
  </el-form-item>
  
  <el-form-item label="备注" :label-width="formLabelWidth">
    <el-input type="textarea" v-model="locationForm.locaTionRember" autocomplete="off" placeholder="请输入" />
  </el-form-item>
</el-form>

<template #footer>
  <div class="dialog-footer">
    <el-button @click="dialogFormVisible = false">取消</el-button>
    <el-button type="primary" @click="confirmAddLocation">
      确定
    </el-button>
  </div>
</template>
</el-dialog>

<!-- 编辑库位弹窗 -->
<el-dialog v-model="editDialogVisible" title="编辑库位" width="500">
<el-form :model="editForm" ref="editFormRef">
  <el-form-item label="库位编号" :label-width="formLabelWidth">
    <el-input v-model="editForm.locaTionNum" autocomplete="off" disabled />
  </el-form-item>
  
  <el-form-item label="库位名称" :label-width="formLabelWidth">
    <el-input v-model="editForm.locaTionName" autocomplete="off" placeholder="请输入" />
  </el-form-item>
  
  <el-form-item label="库位容量/m³" :label-width="formLabelWidth">
    <el-input v-model="editForm.locaTionCapacity" autocomplete="off" placeholder="请输入" />
  </el-form-item>
  
  <el-form-item label="库位主管" :label-width="formLabelWidth">
    <el-select v-model="editForm.locaTionManage" placeholder="请选择">
      <el-option v-for="item in useritems" :label="item.userName" :value="item.userID"></el-option>
    </el-select>
  </el-form-item>
  
  <el-form-item label="库位状态" :label-width="formLabelWidth">
    <el-radio-group v-model="editForm.locaTionCStatus">
      <el-radio label="启用">启用</el-radio>
      <el-radio label="停用">停用</el-radio>
    </el-radio-group>
  </el-form-item>
  
  <el-form-item label="排序" :label-width="formLabelWidth">
    <el-input v-model="editForm.locaTionSort" autocomplete="off" placeholder="请输入" />
  </el-form-item>
  
  <el-form-item label="备注" :label-width="formLabelWidth">
    <el-input type="textarea" v-model="editForm.locaTionRember" autocomplete="off" placeholder="请输入" />
  </el-form-item>
</el-form>

<template #footer>
  <div class="dialog-footer">
    <el-button @click="editDialogVisible = false">取消</el-button>
    <el-button type="primary" @click="saveEdit">保存</el-button>
  </div>
</template>
</el-dialog>

<el-button type="primary" @click="AddWhouseLocation()">确认</el-button>
</template>

<script setup>
import axios from 'axios';
import { ref, reactive, onMounted } from 'vue';
import { ElMessage ,ElMessageBox} from 'element-plus';
import {useRoute,useRouter} from 'vue-router'

const router=useRouter();
const route=useRoute();


// 基础信息表单数据
const form = reactive({
  warehouse: {
    "whouseNum": `CKBH${Math.floor(Math.random() * (999999 - 100000 + 1)) + 100000}`,
    "whouseName": "",
    "capacity": "",
    "dementperId": '',
    "manager": '',
    "phone": "",
    "wHouseAddr": "",
    "sort": '',
    "state": false,
    "lock": false,
    "rember": ''
  },
  locations: [] // 修改这里，初始化为空数组
})
//编辑库位弹框数据
const editForm = reactive({
locaTionNum: '',
locaTionName: '',
locaTionCapacity: '',
locaTionManage: 0,
locaTionCStatus: '启用',
locaTionSort: '',
locaTionRember: '',
})

// 新增库位表单数据
const locationForm = reactive({
locaTionNum: '',
locaTionName: '',
locaTionCapacity: '',
locaTionManage: 0,
locaTionCStatus: '启用',
locaTionSort: '',
locaTionRember: ''
})

const departments = ref([]);
const users = ref([]);
const tableRef = ref(null);
onMounted(() => {
  getDepartments();//初始化部门
  getDepidByUser();//根据部门查询人员
})

// 获取部门列表
const getDepartments = () => {
  axios({
    url: 'http://localhost:5170/api/User/QueryDepent',
    method: 'get',
  })
  .then(res => {
    if(res.data.code == 101) {
      departments.value = res.data.list;
    }
  })
  .catch(error => {
    console.error('获取部门列表失败:', error);
    ElMessage.error('获取部门列表失败');
  })
}

// 部门选择变化时获取对应部门的主管列表
const handleDepartmentChange = (departmentId) => {
  // 清空之前选择的主管和电话
  form.warehouse.manager = '';
  form.warehouse.phone = '';
  
  if (!departmentId) {
    users.value = [];
    return;
  }
  
  axios({
    url: 'http://localhost:5170/api/User/GetDepIdUser',
    method: 'get',
    params: {
      DepermentID: departmentId
    }
  })
  .then(res => {
    if(res.data.code == 101) {
      users.value = res.data.list;
      // 如果只有一个主管，自动选中
      if (users.value.length === 1) {
        form.warehouse.manager = users.userID;
        // 自动获取该主管的电话
        handleUserChange(users.userID);
      }
    } else {
      users.value = [];
    }
  })
  .catch(error => {
    console.error('获取部门用户失败:', error);
    ElMessage.error('获取部门主管列表失败');
    users.value = [];
  })
}

// 用户选择变化时获取用户电话
const handleUserChange = (userId) => {
  // 清空电话
  form.warehouse.phone = '';
  
  if (!userId) return;
  
  axios({
    url: 'http://localhost:5170/api/User/GetUserPhone',
    method: 'get',
    params: {  // 注意这里应该是params而不是直接放在data中
      UserID: userId
    }
  })
  .then(res => {
    if(res.data.code == 101) {
      console.log('用户的联系方式',res)
      form.warehouse.phone = res.data.data.userPhone;
    } else {
      ElMessage.warning('未获取到用户电话信息');
    }
  })
  .catch(error => {
    console.error('获取用户电话失败:', error);
    ElMessage.error('获取用户电话失败');
  })
}

const useritems=ref([]);
//根据部门查询部门成员
const getDepidByUser=()=>{
  axios({
    url:'http://localhost:5170/api/User/GetDepIdUser',
    method:'get',
    params:{
      DepermentID:1
    }
  })
  .then(res=>{
    if(res.data.code==101){
      useritems.value=res.data.list;
    }
  })
}
  
// 新增库位方法
const addLocation = () => {
// 重置表单数据
Object.assign(locationForm, {
  locaTionNum: `KWBH${Math.floor(Math.random() * (999999 - 100000 + 1)) + 100000}`,
  locaTionName: '',
  locaTionCapacity: '',
  locaTionManage: '',
  locaTionCStatus: '启用',
  locaTionSort: '',
  locaTionRember: ''
})
dialogFormVisible.value = true
}

// 确认新增库位
const confirmAddLocation = () => {
// 添加到库位列表
form.locations.push({
  locaTionNum: locationForm.locaTionNum,
  locaTionName: locationForm.locaTionName,
  locaTionCapacity: locationForm.locaTionCapacity,
  locaTionManage: locationForm.locaTionManage,
  locaTionCStatus: locationForm.locaTionCStatus,
  locaTionSort: locationForm.locaTionSort,
  locaTionRember: locationForm.locaTionRember
})

dialogFormVisible.value = false
ElMessage.success('库位添加成功')
}
// 编辑库位方法
const editLocation = (row) => {
const index = form.locations.findIndex(item => item.locaTionNum === row.locaTionNum)
if (index !== -1) {
  // 填充表单数据
  Object.assign(editForm, {
    ...row,
    index
  })
  editDialogVisible.value = true
}
}

// 保存编辑
const saveEdit = () => {
if (editForm.index !== -1) {
  // 更新库位数据
  form.locations[editForm.index] = {
    locaTionNum: editForm.locaTionNum,
    locaTionName: editForm.locaTionName,
    locaTionCapacity: editForm.locaTionCapacity,
    locaTionManage: editForm.locaTionManage,
    locaTionCStatus: editForm.locaTionCStatus,
    locaTionSort: editForm.locaTionSort,
    locaTionRember: editForm.locaTionRember
  }
  
  editDialogVisible.value = false
}
}
  
// 导入库位方法
const importLocations = () => {
  console.log('导入库位')
}
  
// 导出库位方法
const exportLocations = () => {
  console.log('导出库位')
}
  
  
// 删除选中库位方法
const deleteLocation = () => {
const selectedRows = tableRef.value?.getSelectionRows() || [];
console.log('选中的数据长度',selectedRows.length)
if (selectedRows.length === 0) {
  ElMessage.warning('请先选择要删除的库位');
  return;
}

ElMessageBox.confirm('确定要删除选中的库位吗？', '提示', {
  confirmButtonText: '确定',
  cancelButtonText: '取消',
  type: 'warning'
}).then(() => {
  const selectedIndexes = selectedRows.map(row => 
    form.locations.findIndex(item => item.locaTionNum === row.locaTionNum)
  );
  selectedIndexes.sort((a, b) => b - a).forEach(index => {
    form.locations.splice(index, 1);
  });
  ElMessage.success('删除成功');
}).catch(() => {
  ElMessage.info('已取消删除');
});
}

// 删除单个库位方法
const deleteSingleLocation = (row) => {
ElMessageBox.confirm('确定要删除该库位吗？', '提示', {
  confirmButtonText: '确定',
  cancelButtonText: '取消',
  type: 'warning'
}).then(() => {
  const index = form.locations.findIndex(item => item.locaTionNum === row.locaTionNum);
  if (index !== -1) {
    form.locations.splice(index, 1);
    ElMessage.success('删除成功');
  }
}).catch(() => {
  ElMessage.info('已取消删除');
});
}

const dialogFormVisible = ref(false)
// 编辑相关状态
const editDialogVisible = ref(false)
const formLabelWidth = '140px'

const AddWhouseLocation=()=>{
axios({
  url:'http://localhost:5162/api/User/AddWhouse',
  method:'post',
  data:form
})
.then(res=>{
  console.log(form.locations)
  if(res.status==200){
    ElMessage.success('操作成功');
    router.push("/ShowWhouse")
  }
})
}

</script>
  
<style scoped>
/* 可以添加一些自定义样式 */
</style>